package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.IteratorUtils;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.id.IdUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.util.H5DomainUrlUtils;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyHaoXinHuaV3;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeHaoXinHuaV3;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformMultiPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMaskConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/** 安心分期-V3&8位好鑫花全流程8.2
 * @ Author 江小游
 * @ Date 2025/5/29 16:45
 */
@ApiPlan(productId = "1", type = ApiPlanConvertType.PLAT_PHONE_MASK)
public class ApiPlatHaoXinHuaPhoneMd5ConvertV3 implements ApiPlatformPhoneMaskConvertHandler {

    public static final String KEY = "4YADG0696u27kYsM";
    public static final String CHANNEL_ID = "y8gW2juC";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) {
        ApiPlatDataExchangeHaoXinHuaV3 data = new ApiPlatDataExchangeHaoXinHuaV3();
        ApiFieldConverter apiFieldConverter=ApiFieldConverter.create(apiDataExchangeParameter);
        // 手机号MD5
        data.setPhoneMd5(apiDataExchangeParameter.getPhoneMd5());
        // 手机号掩码
        data.setPhonePrefix(apiDataExchangeParameter.getPhoneMask());
        // 姓名
        data.setUserName("浩安星");
        // 年龄
        data.setAge(apiFieldConverter.getAgeInt());
        //  性别 0-女 1-男 默认1
        String sex = apiDataExchangeParameter.getSex();
        Integer sexChoose = ChooseEq.create()
                .when(sex, "0", 1)
                .when(sex, "1", 0)
                .end(1);
        data.setSex(sexChoose);
        //  城市编码
        data.setAreaCode(apiDataExchangeParameter.getAreaCode());
        //  城市
        data.setCity(apiDataExchangeParameter.getCity());
        //  芝麻分
        Integer zhima = ChooseEq.create()
                .when(apiDataExchangeParameter.getSesameCredit(), "1", 2)
                .when(apiDataExchangeParameter.getSesameCredit(), "2", 3)
                .when(apiDataExchangeParameter.getSesameCredit(), "3", 4)
                .when(apiDataExchangeParameter.getSesameCredit(), "4", 5)
                .end(2);
        data.setSesameCredit(zhima);
        //  公积金
        Integer gongjijin = ChooseEq.create()
                .when(apiDataExchangeParameter.getProvidentFund(), "1", 1)
                .when(apiDataExchangeParameter.getProvidentFund(), "2", 2)
                .when(apiDataExchangeParameter.getProvidentFund(), "3", 2)
                .when(apiDataExchangeParameter.getProvidentFund(), "4", 2)
                .end(1);
        data.setProvidentFund(gongjijin);
        //  社保
        Integer shebao = ChooseEq.create()
                .when(apiDataExchangeParameter.getSocialSecurity(), "1", 1)
                .when(apiDataExchangeParameter.getSocialSecurity(), "2", 2)
                .when(apiDataExchangeParameter.getSocialSecurity(), "3", 2)
                .when(apiDataExchangeParameter.getSocialSecurity(), "4", 2)
                .end(1);
        data.setSocialSecurity(shebao);
        //  保单
        Integer baodanIs = ChooseEq.create()
                .when(apiDataExchangeParameter.getInsurancePolicy(), "1", 1)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "2", 2)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "3", 2)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "4", 2)
                .end(1);
        data.setInsurancePolicy(baodanIs);
        //  房产情况
        Integer house = ChooseEq.create()
                .when(apiDataExchangeParameter.getRealEstateInfo(), "1", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "2", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "3", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "4", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "5", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "6", 2)
                .end(1);
        data.setRealEstateInfo(house);
        //  车产
        Integer car = ChooseEq.create()
                .when(apiDataExchangeParameter.getCarInfo(), "1", 1)
                .when(apiDataExchangeParameter.getCarInfo(), "2", 2)
                .when(apiDataExchangeParameter.getCarInfo(), "3", 2)
                .when(apiDataExchangeParameter.getCarInfo(), "4", 2)
                .end(1);
        data.setCarInfo(car);
        //  职业
        Integer job = ChooseEq.create()
                .when(apiDataExchangeParameter.getCareer(), "1", 1)
                .when(apiDataExchangeParameter.getCareer(), "2", 5)
                .when(apiDataExchangeParameter.getCareer(), "3", 3)
                .when(apiDataExchangeParameter.getCareer(), "4", 2)
                .when(apiDataExchangeParameter.getCareer(), "5", 4)
                .end(1);
        data.setCareer(job);
        //  营业执照
        Integer bizLicenseYear = ChooseEq.create()
                .when(apiDataExchangeParameter.getBizLicenseYear(), "1", 1)
                .when(apiDataExchangeParameter.getBizLicenseYear(), "2", 2)
                .when(apiDataExchangeParameter.getBizLicenseYear(), "3", 3)
                .when(apiDataExchangeParameter.getBizLicenseYear(), "4", 4)
                .end(1);
        data.setBizLicenseYear(bizLicenseYear);
        //  贷款金额
        Integer money = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanAmount(), "1", 30000)
                .when(apiDataExchangeParameter.getLoanAmount(), "2", 50000)
                .when(apiDataExchangeParameter.getLoanAmount(), "3", 100000)
                .when(apiDataExchangeParameter.getLoanAmount(), "4", 200000)
                .end(30000);
        data.setLoanAmount(money);
        //  ip
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getIp())) {
            data.setIp(apiDataExchangeParameter.getIp());
        } else {
            data.setIp("127.0.0.1");
        }
        //  客户端类型
        data.setPlatform(1);
        //  月收入
        Integer monthlySalary = ChooseEq.create()
                .when(apiDataExchangeParameter.getMonthlySalary(), "1", 1)
                .when(apiDataExchangeParameter.getMonthlySalary(), "2", 2)
                .when(apiDataExchangeParameter.getMonthlySalary(), "3", 3)
                .when(apiDataExchangeParameter.getMonthlySalary(), "4", 4)
                .when(apiDataExchangeParameter.getMonthlySalary(), "5", 6)
                .end(1);
        data.setMonthlySalary(monthlySalary);
        // 信用卡  信用卡 0:无信用卡 1:1-5万 2:5-10万 3:10-20万 4:20万以上 默认0
        Integer hasCredit=ChooseEq.create()
                .when(apiDataExchangeParameter.getCreditLimit(), "1", 0)
                .when(apiDataExchangeParameter.getCreditLimit(), "2", 1)
                .when(apiDataExchangeParameter.getCreditLimit(), "3", 1)
                .when(apiDataExchangeParameter.getCreditLimit(), "4", 1)
                .when(apiDataExchangeParameter.getCreditLimit(), "5", 2)
                .when(apiDataExchangeParameter.getCreditLimit(), "6", 1)
                .end(0);
        data.setHasCredit(hasCredit);
        // 信用记录  1-无逾期 2-有逾期
        Integer creditHistory=ChooseEq.create()
                .when(apiDataExchangeParameter.getOverdue(), "1", 1)
                .when(apiDataExchangeParameter.getOverdue(), "2", 2)
                .when(apiDataExchangeParameter.getOverdue(), "3", 2)
                .end(0);
        data.setCreditHistory(creditHistory);
        //  花呗 1-无 2-5000以下 3-5000~10000 4-10000以上
        Integer huaBei = ChooseEq.create()
                .when(apiDataExchangeParameter.getHbLimit(), "1", 1)
                .when(apiDataExchangeParameter.getHbLimit(), "2", 2)
                .when(apiDataExchangeParameter.getHbLimit(), "3", 3)
                .when(apiDataExchangeParameter.getHbLimit(), "4", 4)
                .when(apiDataExchangeParameter.getHbLimit(), "5", 4)
                .end(1);
        data.setHasZfb(huaBei);
        //  白条 京东白条情况：1-无 2-5000以下 3-5000以上
        Integer btLimit = ChooseEq.create()
                .when(apiDataExchangeParameter.getBtLimit(), "1", 1)
                .when(apiDataExchangeParameter.getBtLimit(), "2", 2)
                .when(apiDataExchangeParameter.getBtLimit(), "3", 3)
                .when(apiDataExchangeParameter.getBtLimit(), "4", 3)
                .when(apiDataExchangeParameter.getBtLimit(), "5", 3)
                .end(1);
        data.setHasJd(btLimit);
        AES aes = AES.createEcb(KEY.getBytes());
        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(data));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channelCode", CHANNEL_ID);
            newMap.put("content", dataStr);
            newMap.put("serialNo", IdUtils.getSimpleUuid());
        });
        return JsonUtils.toJson(map);
    }


    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) {
        ApiPlatApplyHaoXinHuaV3 data = new ApiPlatApplyHaoXinHuaV3();
        ApiFieldConverter apiFieldConverter=ApiFieldConverter.create(apiApplyParameter);
        // 撞库id
        data.setApplyNo(apiApplyParameter.dataExchangeApplyId());
        // 电话
        data.setPhone(apiApplyParameter.getPhone());
        // 姓名
        data.setUserName(apiApplyParameter.getUserName());
        // 年龄
        data.setAge(apiFieldConverter.getAgeInt());
        //  性别 0-女 1-男 默认1
        Integer sexChoose = ChooseEq.create()
                .when(apiApplyParameter.getSex(), "0", 1)
                .when(apiApplyParameter.getSex(), "1", 0)
                .end(1);
        data.setSex(sexChoose);
        //  城市编码
        data.setAreaCode(apiApplyParameter.getAreaCode());
        //  城市
        data.setCity(apiApplyParameter.getCity());
        //  芝麻分
        Integer zhima = ChooseEq.create()
                .when(apiApplyParameter.getSesameCredit(), "1", 2)
                .when(apiApplyParameter.getSesameCredit(), "2", 3)
                .when(apiApplyParameter.getSesameCredit(), "3", 4)
                .when(apiApplyParameter.getSesameCredit(), "4", 5)
                .end(2);
        data.setSesameCredit(zhima);
        //  公积金
        Integer gongjijin = ChooseEq.create()
                .when(apiApplyParameter.getProvidentFund(), "1", 1)
                .when(apiApplyParameter.getProvidentFund(), "2", 2)
                .when(apiApplyParameter.getProvidentFund(), "3", 2)
                .when(apiApplyParameter.getProvidentFund(), "4", 2)
                .end(1);
        data.setProvidentFund(gongjijin);
        //  社保
        Integer shebao = ChooseEq.create()
                .when(apiApplyParameter.getSocialSecurity(), "1", 1)
                .when(apiApplyParameter.getSocialSecurity(), "2", 2)
                .when(apiApplyParameter.getSocialSecurity(), "3", 2)
                .when(apiApplyParameter.getSocialSecurity(), "4", 2)
                .end(1);
        data.setSocialSecurity(shebao);
        //  保单
        Integer baodanIs = ChooseEq.create()
                .when(apiApplyParameter.getInsurancePolicy(), "1", 1)
                .when(apiApplyParameter.getInsurancePolicy(), "2", 2)
                .when(apiApplyParameter.getInsurancePolicy(), "3", 2)
                .when(apiApplyParameter.getInsurancePolicy(), "4", 2)
                .end(1);
        data.setInsurancePolicy(baodanIs);
        //  房产情况
        Integer house = ChooseEq.create()
                .when(apiApplyParameter.getRealEstateInfo(), "1", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "2", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "3", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "4", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "5", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "6", 2)
                .end(1);
        data.setRealEstateInfo(house);
        //  车产
        Integer car = ChooseEq.create()
                .when(apiApplyParameter.getCarInfo(), "1", 1)
                .when(apiApplyParameter.getCarInfo(), "2", 2)
                .when(apiApplyParameter.getCarInfo(), "3", 2)
                .when(apiApplyParameter.getCarInfo(), "4", 2)
                .end(1);
        data.setCarInfo(car);
        //  职业
        Integer job = ChooseEq.create()
                .when(apiApplyParameter.getCareer(), "1", 1)
                .when(apiApplyParameter.getCareer(), "2", 5)
                .when(apiApplyParameter.getCareer(), "3", 3)
                .when(apiApplyParameter.getCareer(), "4", 2)
                .when(apiApplyParameter.getCareer(), "5", 4)
                .end(1);
        data.setCareer(job);
        //  营业执照
        Integer bizLicenseYear = ChooseEq.create()
                .when(apiApplyParameter.getBizLicenseYear(), "1", 1)
                .when(apiApplyParameter.getBizLicenseYear(), "2", 2)
                .when(apiApplyParameter.getBizLicenseYear(), "3", 3)
                .when(apiApplyParameter.getBizLicenseYear(), "4", 4)
                .end(1);
        data.setBizLicenseYear(bizLicenseYear);
        //  贷款金额
        Integer money = ChooseEq.create()
                .when(apiApplyParameter.getLoanAmount(), "1", 30000)
                .when(apiApplyParameter.getLoanAmount(), "2", 50000)
                .when(apiApplyParameter.getLoanAmount(), "3", 100000)
                .when(apiApplyParameter.getLoanAmount(), "4", 200000)
                .end(30000);
        data.setLoanAmount(money);
        //  ip
        if (ValidParam.isNotEmpty(apiApplyParameter.getIp())) {
            data.setIp(apiApplyParameter.getIp());
        } else {
            data.setIp("127.0.0.1");
        }
        //  客户端类型
        data.setPlatform(1);
        //  月收入
        Integer monthlySalary = ChooseEq.create()
                .when(apiApplyParameter.getMonthlySalary(), "1", 1)
                .when(apiApplyParameter.getMonthlySalary(), "2", 2)
                .when(apiApplyParameter.getMonthlySalary(), "3", 3)
                .when(apiApplyParameter.getMonthlySalary(), "4", 4)
                .when(apiApplyParameter.getMonthlySalary(), "5", 6)
                .end(1);
        data.setMonthlySalary(monthlySalary);
        // 协议列表
        data.setProtocolList(CollUtils.newArrayList(newList -> {
            ApiPlatApplyHaoXinHuaV3.ProtocolList protocolList = new ApiPlatApplyHaoXinHuaV3.ProtocolList();
            protocolList.setProtocolName("个人信息授权协议");
            protocolList.setProtocolUrl(H5DomainUrlUtils.createUserProtocolUrl(apiApplyParameter.getProductPlanId(), apiApplyParameter.getPhoneMd5()));
            newList.add(protocolList);
        }));
        // 加密
        AES aes = AES.createEcb(KEY.getBytes());
        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(data));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channelCode", CHANNEL_ID);
            newMap.put("content", dataStr);
            newMap.put("serialNo", IdUtils.getSimpleUuid());
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMaskApply respApply(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        return RespPlatformPhoneMaskApply.ofSuc();
    }

    @Override
    public RespPlatformMultiPhoneMaskDataExchange respDataExchange(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }

        JSONArray resData = JsonUtils.get(respJson).getJSONArray("data");
        if (ValidParam.isEmpty(resData)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }

        RespPlatformMultiPhoneMaskDataExchange respPlatformMultiPhoneMaskDataExchange = RespPlatformMultiPhoneMaskDataExchange.ofSuc();
        List<RespPlatformPhoneMaskDataExchange> listRespPlatformPhoneMaskDataExchange = CollUtils.newArrayList();
        for (int i = 0; i < resData.size(); i++) {
            JSONObject item = resData.getJSONObject(i);
            if (ValidParam.isNotNull(item)) {
                BigDecimal price = item.getBigDecimal("price");
                String companyName = item.getString("companyName");
                String productName = item.getString("productName");
                String logo = item.getString("logo");
                String orderId = item.getString("applyNo");

                List<ApiProtocol> protocolList = CollUtils.newArrayList(newList -> {
                    //  获取协议
                    JSONArray listProtocolResult = item.getJSONArray("protocolList");
                    IteratorUtils.array(listProtocolResult, (protocolResult, index) -> {
                        JSONObject protocolObject = listProtocolResult.getJSONObject(index);
                        ApiProtocol protocol = new ApiProtocol();
                        protocol.setProtocolName(protocolObject.getString("protocolName"));
                        protocol.setProtocolUrl(protocolObject.getString("protocolUrl"));
                        newList.add(protocol);
                    });
                });

                RespPlatformPhoneMaskDataExchange result = RespPlatformPhoneMaskDataExchange.of();

                result.setPrice(price);
                result.setLogoPath(logo);
                result.setDisplayName(companyName);
                result.setProductName(productName);
                result.setApplyId(orderId);
                result.setProtocolList(protocolList);
                listRespPlatformPhoneMaskDataExchange.add(result);
            }
        }
        respPlatformMultiPhoneMaskDataExchange.setListPhoneMask(listRespPlatformPhoneMaskDataExchange);
        return respPlatformMultiPhoneMaskDataExchange;
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        JSONObject jsonObject = JsonUtils.get(requestVO.getBody());
        String phoneMd5 = jsonObject.getString("phoneMd5");
        String orderId = jsonObject.getString("applyNo");

        RespPlatformNoticeApply applyNotice = new RespPlatformNoticeApply();
        applyNotice.setPhoneMd5(phoneMd5);
        applyNotice.setApplyId(orderId);
        return applyNotice;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        boolean b = apiBizStatus.hasBizSuc();
        if (b) {
            return MapUtils.newHashMap(newHashMap -> {
                newHashMap.put("code", 200);
                newHashMap.put("msg", "通知进件成功");
            });
        }
        return MapUtils.newHashMap(newHashMap -> {
            newHashMap.put("code", "500");
            newHashMap.put("msg", apiBizStatus.getBizMsg());
        });
    }
}
